package com.tanhua.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.TaoHuaApi;
import com.tanhua.dubbo.server.pojo.TaoHua;
import com.tanhua.server.vo.ChuanYin;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
public class TaoHuaService {
    @Reference(version = "1.0.0")
    private TaoHuaApi taoHuaApi;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private UserInfoMapper userInfoMapper;

    public String FaSongYuYin(MultipartFile multipartFile){
        try {
            User user = UserThreadLocal.get();
            TaoHua taoHua = new TaoHua();
            taoHua.setUserId(user.getId());
            taoHua.setTaohuatime(new Date());

            //上传语音到FastDFS中
            StorePath storePath = this.storageClient.uploadFile(multipartFile.getInputStream(),
                    multipartFile.getSize(),
                    StrUtil.subAfter(multipartFile.getOriginalFilename(), '.', true),
                    null);

            String yyurl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            taoHua.setTaohuaurl(yyurl);
            return this.taoHuaApi.saveYY(taoHua);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ChuanYin JieShouYuYin() {
        try {
            User user = UserThreadLocal.get();

            TaoHua taoHua = this.taoHuaApi.saveCy();
            UserInfo userInfo = this.userInfoMapper.selectById(taoHua.getUserId());

            ChuanYin chuanYin=new ChuanYin();
            chuanYin.setId(ObjectId.get());
            chuanYin.setUfoid(userInfo.getUserId());
            chuanYin.setAvatar(userInfo.getLogo());
            chuanYin.setNickname(userInfo.getNickName());
            chuanYin.setGender(userInfo.getSex().getValue()==1?"男":"女");
            chuanYin.setAge(userInfo.getAge());
            chuanYin.setSoundUrl(taoHua.getTaohuaurl());
            Long count = this.taoHuaApi.YyCount(user.getId());
            chuanYin.setRemainingTimes(Convert.toInt(10-count));
            return chuanYin;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
